package com.atguigu.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.msmservice.service.MsmService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 发送短信
 */
@Service
public class MsmServiceImpl implements MsmService {

    @Override
    public Boolean send(String phone, HashMap<String, String> parammap) {

        if (StringUtils.isEmpty(phone)) {
            return false;
        }

//        创建一个发送短信的对象内置对象，里面包含阿里云的key和授权码
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI5t9VGBUJrmZNv2yHGn2A", "jJYDVYFGEPhouuEDpKpa9CU3gQCTAf");
//        创建发送短信类，传入发送短信需要的认证信息
        IAcsClient client = new DefaultAcsClient(profile);
//     创建一个request请求对象放到发送短信类做加载
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);固定参数
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);//设置手机号
        request.putQueryParameter("SignName", "阿里云短信测试");//签名
        request.putQueryParameter("TemplateCode", "SMS_154950909");//模板编号
        //这里用到了fastjson，把map转换成json数据，因为阿里云只接受json对象，所有需要转换，springbootweb默认就有了
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(parammap));

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            System.out.println(response.getHttpResponse().isSuccess());
            return response.getHttpResponse().isSuccess();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;


    }
}
